package com.hao.crud.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hao.crud.bean.Employee;
import com.hao.crud.bean.Msg;
import com.hao.crud.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author hao   email：huanghao.0508@qq.com
 * @ClassName：EmpController
 * @description ：TODO
 * @create 2020-10-28-15:01
 */
@Controller
public class EmpController {

    @Autowired
    private EmployeeService employeeService;

/*    @RequestMapping(value = "emps")
    public String getEmps(@RequestParam(value = "pn",defaultValue = "1") Integer pn, Model model){
//        在查询之间设置Page的页码，和每页数据量
        PageHelper.startPage(pn,5);
//        获取所有的Employee对象
        List<Employee> employees = employeeService.getAll();
//        获取分页信息对象
        PageInfo<Employee> pageInfo = new PageInfo<>(employees);
//        将分页信息对象放入req域中
        model.addAttribute("pageInfo",pageInfo);

        return "list";
    } */

    @RequestMapping(value = "emps")
    @ResponseBody
    public Msg getEmps(@RequestParam(value = "pn",defaultValue = "1") Integer pn){
//        在查询之间设置Page的页码，和每页数据量
        PageHelper.startPage(pn,5);
//        获取所有的Employee对象
        List<Employee> employees = employeeService.getAll();
//        获取分页信息对象
        PageInfo<Employee> pageInfo = new PageInfo<>(employees,5);
//        使用Msg传递信息给客户端
        return Msg.success().add("pageInfo",pageInfo);
    }
    @RequestMapping(value = "emps" ,method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteEmps(String ids){
        //判断是由多个id
        if(ids.contains("-")){
            String[] idsStr = ids.split("-");
            List<Integer> idsInt = new ArrayList<>();
//            将其转化成Integer类型的List集合
            for (String id : idsStr) {
                idsInt.add(Integer.valueOf(id));
            }
            employeeService.deleteEmpAll(idsInt);
        }else{
            Integer id = Integer.valueOf(ids);
            employeeService.deleteEmp(id);
        }

        return Msg.success();
    }
    @RequestMapping(value = {"emp"},method = RequestMethod.POST)
    @ResponseBody
    public Msg addEmp(@Valid Employee emp, BindingResult result){//@Valid 表达式该参数需要进行验证，result里面是验证的结果
        //判断是否有误
        if (result.hasErrors()){
            Map<String,String> errorMap = new HashMap<>();
            //获取错误信息
            List<FieldError> errors = result.getFieldErrors();
//            遍历errors，将错误属性放入Map中
            for (FieldError fieldError : errors) {
                errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            return Msg.fail().add("errorMap",errorMap);
        }else{
            employeeService.save(emp);
            return Msg.success();
        }
    }
    /**
     * @param: empId 员工id
     * @description: TODO 根据员工id查询员工
     * @return: com.hao.crud.bean.Msg
     * @author: hao
     * @date: 2020/10/31
     */
    @RequestMapping(value = {"emp"},method = RequestMethod.GET)
    @ResponseBody
    public Msg selectEmp(Integer empId){//@Valid 表达式该参数需要进行验证，result里面是验证的结果
        Employee emp =  employeeService.selectEmpById(empId);
        if (emp==null){
            return Msg.fail();
        }else{
            return Msg.success().add("emp",emp);
        }
    }
    @RequestMapping(value = {"emp"},method = RequestMethod.PUT)
    @ResponseBody
    public Msg updateEmp(@Valid Employee emp, BindingResult result){//@Valid 表达式该参数需要进行验证，result里面是验证的结果
        //判断是否有误
        if (result.hasErrors()){
            Map<String,String> errorMap = new HashMap<>();
            //获取错误信息
            List<FieldError> errors = result.getFieldErrors();
//            遍历errors，将错误属性放入Map中
            for (FieldError fieldError : errors) {
                errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            return Msg.fail().add("errorMap",errorMap);
        }else{
            employeeService.updateEmp(emp);
            return Msg.success();
        }
    }
    @RequestMapping(value = {"emp"},method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteEmp(Employee emp){//@Valid 表达式该参数需要进行验证，result里面是验证的结果
        employeeService.deleteEmp(emp.getEmpId());
        return Msg.success();
    }
    //    检查用户是否存在
    @RequestMapping("checkUser")
    @ResponseBody
    public Msg checkUser(String empName){
        Msg msg;
        boolean isExist = employeeService.checkUser(empName);
        if (isExist){
            msg=Msg.success();
            msg.setMsg("");
        }else{
            msg=Msg.fail();
            msg.setMsg("用户名已存在");
        }
        return msg;
    }
}
